package cn.sytton.taffe.framework.xss;

import cn.hutool.core.util.StrUtil;
import io.micrometer.core.instrument.util.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}

	/**
	 * 覆盖getParameter方法，将参数名和参数值都做xss过滤。
	 * 如果需要获得原始的值，则通过super.getParameterValues(name)来获取
	 * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
	 */
	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if (StrUtil.isNotEmpty(value)) {
			value = JsoupUtil.clean(value);
		}
		return value;
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] arr = super.getParameterValues(name);
		if(arr != null){
			for (int i=0;i<arr.length;i++) {
				arr[i] = JsoupUtil.clean(arr[i]);
			}
		}
		return arr;
	}

	//在使用@RequestBody情况,参数并不是封装在parameter里面
	@Override
	public ServletInputStream getInputStream() throws IOException {
		// 非json类型，直接返回
		if (!isJsonRequest()) {
			return super.getInputStream();
		}

		// 为空，直接返回
		String json = IOUtils.toString(super.getInputStream(), StandardCharsets.UTF_8);
		if (!StringUtils.hasText(json)) {
			return super.getInputStream();
		}

		// xss过滤
		json = JsoupUtil.clean(json);
		byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);
		final ByteArrayInputStream bis = new ByteArrayInputStream(jsonBytes);
		return new ServletInputStream() {
			@Override
			public boolean isFinished()
			{
				return true;
			}

			@Override
			public boolean isReady()
			{
				return true;
			}

			@Override
			public void setReadListener(ReadListener readListener) {}

			@Override
			public int available() {
				return jsonBytes.length;
			}

			@Override
			public int read() {
				return bis.read();
			}
		};
	}

	/**
	 * 是否是Json请求
	 */
	public boolean isJsonRequest() {
		String header = super.getHeader(HttpHeaders.CONTENT_TYPE);
		return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
	}
}
